//
//  ViewController.m
//  iFeller
//
//  Created by Wii on 15/12/10.
//  Copyright © 2015年 Wii. All rights reserved.
//

#import "WiiHomeViewController.h"
#import "WiiAddTaskViewController.h"
#import "WiiTaskDetailViewController.h"
#import "WiiTableHeader.h"
#import "WiiMenu.h"
#import "UITableView+EmptyData.h"
#import "WiiSegue.h"
#import "XYTableViewCell.h"
#import "XYChangeDateController.h"
#import "WiiHomeModel.h"
#import "WiiCalendarViewController.h"
#import "XYLocalPush.h"

typedef NS_ENUM (NSInteger,WiiBarButton){
    WiiBarButtonTime = 100,
    WiiBarButtonList ,
    WiiBarButtonOK ,
    WiiBarButtonAdd
};
typedef NS_ENUM (NSInteger,WiiMenuButton){
    WiiMenuButtonShow = 200,
    WiiMenuButtonCalendar
};

typedef NS_ENUM (NSInteger, XYCELLStatus) {
    XYCellTimeStatus = 0,
    XYCellListStatus ,
    XYCellOkStatus
};
//日历控制器出现状态
typedef NS_ENUM (NSInteger, XYCalenderStatus) {
    XYCalenderStatusOut = 0,
    XYCalenderStatusIn ,
};

static NSString *XYIdentifier = @"XYCELL";
@interface WiiHomeViewController () <UITableViewDelegate,UITableViewDataSource,WiiMenuDelegate,XYTableViewCellDelegate, WiiTaskDetailViewControllerDelegate>

@property (nonatomic , strong) UIImageView *navBarBG;
@property (nonatomic , strong) UITableView *mainTableView;
@property (weak, nonatomic) IBOutlet UIButton *addNewTaskButtom;
@property (weak, nonatomic) IBOutlet UIButton *menuButton;
@property (weak, nonatomic) IBOutlet UIButton *calendarButton;
@property (weak, nonatomic) IBOutlet UIButton *delButton;
@property (weak, nonatomic) IBOutlet UIButton *notButton;

@property (nonatomic , strong) UIButton *listButton;

@property (nonatomic , strong) NSMutableArray *dataSource;
@property (nonatomic , strong) WiiTableHeader *header;
@property (nonatomic , strong) WiiMenu *wiiMenu;
@property (nonatomic , strong) NSMutableArray *menuItems;
@property (nonatomic , strong) WiiHomeModel *model;

@property (nonatomic, assign) NSInteger XYCellStatus; /*cell状态 闹钟 待办 完成*/
@end

@implementation WiiHomeViewController

#pragma mark - View lift

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    //去除导航栏下方的横线
    self.navBarBG.hidden = YES;
    
    // 打开数据库
    [self.model.sql openDataBase];
    self.mainTableView.tableFooterView = [[UIView alloc] init];
    [self.mainTableView reloadData];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navBarBG.hidden = NO;
    // 关闭数据库
    [self.model.sql closeTheDataBase];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self registeredNotification];
    [self initDataSource];
    [self initUserInterface];
    [self makeMenu];
    [self makeTopBar];
    //添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notice:) name:@"front" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notice:) name:@"backToForeGround" object:nil];
}

- (void)initDataSource{
    self.XYCellStatus = 1;
    self.dataSource = [NSMutableArray arrayWithArray:[self.model getMyTaskData]];
    [self.mainTableView reloadData];
}

- (void)initUserInterface{
    self.navBarBG = [WiiKit findHairlineImageViewUnder:self.navigationController.navigationBar];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.mainTableView];
    [self.view addSubview:self.addNewTaskButtom];
}
#pragma mark - Make Menu
- (void)makeMenu{
    self.menuItems = [NSMutableArray array];
    [self.menuItems addObject:self.calendarButton];
    [self.menuItems addObject:self.delButton];
    [self.menuItems addObject:self.notButton];
    self.wiiMenu = [[WiiMenu alloc]initWiiMenuWithMenuButton:self.menuButton menuItems:self.menuItems AddButton:self.addNewTaskButtom];
    self.wiiMenu.delegate = self;
    [self.view addSubview:self.menuButton];
    [self.view addSubview:self.calendarButton];
    [self.view addSubview:self.notButton];
}
#pragma mark - 顶部菜单
- (void)makeTopBar{
    //改1 UIButtonTypeSystem->UIButtonTypeCustom 
    UIButton *listButton = [UIButton buttonWithType:UIButtonTypeCustom];
    listButton.frame = CGRectMake(WiiZero, WiiZero, WiiButtonSize, WiiButtonSize);
    listButton.center = CGPointMake(180, 20);
    [listButton setBackgroundImage:[UIImage imageNamed:@"List"] forState:UIControlStateNormal];
    [listButton setBackgroundImage:[UIImage imageNamed:@"list_select"] forState:UIControlStateSelected];
    [listButton addTarget:self action:@selector(topButtonHandle:) forControlEvents:UIControlEventTouchUpInside];
    //起始亮为待办事项
    listButton.selected = YES;
    listButton.tag = WiiBarButtonList;
    self.listButton = listButton;
    
    UIButton *okButton = [UIButton buttonWithType:UIButtonTypeCustom];
    okButton.frame = CGRectMake(WiiZero, WiiZero, WiiButtonSize, WiiButtonSize);
    okButton.center = CGPointMake(230, 20);
    [okButton setBackgroundImage:[UIImage imageNamed:@"OK"] forState:UIControlStateNormal];
    [okButton setBackgroundImage:[UIImage imageNamed:@"ok_select"] forState:UIControlStateSelected];
    okButton.tag = WiiBarButtonOK;
    [okButton addTarget:self action:@selector(topButtonHandle:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *timeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    timeButton.frame = CGRectMake(WiiZero, WiiZero, WiiButtonSize, WiiButtonSize);
    timeButton.center = CGPointMake(130, 20);
    [timeButton setBackgroundImage:[UIImage imageNamed:@"time"] forState:UIControlStateNormal];
    [timeButton setBackgroundImage:[UIImage imageNamed:@"time_select"] forState:UIControlStateSelected];
    timeButton.tag = WiiBarButtonTime;
    [timeButton addTarget:self action:@selector(topButtonHandle:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(WiiZero, WiiZero, SCREEN_WIDTH, 44)];
    [titleView addSubview:listButton];
    [titleView addSubview:okButton];
    [titleView addSubview:timeButton];
    
    [self.navigationItem.titleView sizeToFit];
    self.navigationItem.titleView = titleView;
}

#pragma mark - top button Func

- (void)topButtonHandle:(UIButton *)sender{
    NSArray *titleButtonTag = @[@"100", @"101", @"102"];
    for (int i = WiiZero; i < titleButtonTag.count; i++) {
        int j = [titleButtonTag[i] intValue];
        UIButton *button = (UIButton *)[self.navigationItem.titleView viewWithTag:j];
        if (j == sender.tag) {
            button.selected = YES;
            button.userInteractionEnabled = NO;
            continue;
        }
        button.userInteractionEnabled = YES;
        button.selected = NO;
    }
    
    switch (sender.tag) {
        case WiiBarButtonTime:{
            self.wiiMenu.status = XYCellTimeStatus;
            [UIView animateWithDuration:0.5 animations:^{
                self.addNewTaskButtom.transform = CGAffineTransformMakeTranslation(0, 80);
            }];
            self.dataSource = [NSMutableArray arrayWithArray:[self.model getTheTaskAtHandData]];
            self.XYCellStatus = XYCellTimeStatus;
            [self.mainTableView reloadData];
        }
            NSLog(@"time");
            break;
        case WiiBarButtonList:{
            self.wiiMenu.status = XYCellListStatus;
            [UIView animateWithDuration:0.5 animations:^{
                self.addNewTaskButtom.transform = CGAffineTransformIdentity;
            }];
            self.dataSource = [NSMutableArray arrayWithArray:[self.model getMyTaskData]];
            self.XYCellStatus = XYCellListStatus;
            [self.mainTableView reloadData];
        }
            NSLog(@"list");
            break;
        case WiiBarButtonOK:{
            self.wiiMenu.status = XYCellOkStatus;
            [UIView animateWithDuration:0.5 animations:^{
                self.addNewTaskButtom.transform = CGAffineTransformMakeTranslation(0, 80);
            }];
            self.dataSource = [NSMutableArray arrayWithArray:[self.model getFinishTaskData]];
            self.XYCellStatus = XYCellOkStatus;
            [self.mainTableView reloadData];
        }
            NSLog(@"OK");
            break;
        default:
            break;
    }
}
#pragma mark - modalSegue

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"ShowAddNewTask"]) {
        ((WiiSegue *)segue).targetButton = self.addNewTaskButtom;
        ((WiiSegue *)segue).animationColor = [UIColor greenColor];
    }
}

#pragma mark - WiimenuDelegate

- (void)menuItemsPressed:(UIButton *)button{
    
    if (button == self.calendarButton) {
        WiiCalendarViewController *calendarVC = [[WiiCalendarViewController alloc]init];
        [self.navigationController pushViewController:calendarVC animated:YES];
    }
}
#pragma mark - WIITaskDetailDelegate 
- (void)backToReloadDatasource:(NSInteger)flagOfData {
    switch (flagOfData) {
        case 0:
            self.dataSource = [NSMutableArray arrayWithArray:[self.model getTheTaskAtHandData]];
            [self.mainTableView reloadData];
            break;
        case 1:
            self.dataSource = [NSMutableArray arrayWithArray:[self.model getMyTaskData]];
            [self.mainTableView reloadData];
            break;
        case 2:
            self.dataSource = [NSMutableArray arrayWithArray:[self.model getFinishTaskData]];
            [self.mainTableView reloadData];
            break;
        default:
            break;
    }
}

#pragma mark - <UITableViewDelegate,UITableViewDataSource>

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    [self.mainTableView tableViewDisplayWitMsg:@"没有数据哦!" ifNecessaryForRowCount:self.dataSource.count];
    return self.dataSource.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    WiiTableHeader *header = [[WiiTableHeader alloc]initWithFrame:CGRectMake(WiiZero, WiiZero, SCREEN_WIDTH, 10) dataSource:self.dataSource];
    return header;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    XYTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:XYIdentifier forIndexPath:indexPath];
    //设置cell状态
    cell.cellStatus = self.XYCellStatus;
    [cell setCellpattern:self.dataSource[indexPath.row]];
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WiiTaskDetailViewController *taskDetailVC = [[WiiTaskDetailViewController alloc]init];
    taskDetailVC.dataSource = [self.dataSource[indexPath.row] mutableCopy];
    taskDetailVC.taskStatus = self.XYCellStatus;
    taskDetailVC.delegate = self;
    [self.navigationController pushViewController:taskDetailVC animated:YES];
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{

    [WiiKit mainTableViewCellAnimation:cell];
}

#pragma mark - cell delegate
- (void)deleteTheChoosedCellToLeftOK:(UITableViewCell *)cell {
    NSIndexPath *currentEditingIndexPath = [self.mainTableView indexPathForCell:cell];
    NSMutableArray *array = [self.dataSource[currentEditingIndexPath.row] mutableCopy];
    
    [self.model.sql deleteTheDataBaseWithTableName:TableName_FinishTask deleteName:array[0]];
    [self.model.sql insertDataSourceToDBwithArray:array tableName:TableName_MyTask];
    
    [self.dataSource removeObjectAtIndex:currentEditingIndexPath.row];
    [self.mainTableView deleteRowsAtIndexPaths:@[currentEditingIndexPath] withRowAnimation:UITableViewRowAnimationFade];
}

//向左删除
- (void)deleteTheChoosedCellToLeft:(XYTableViewCell *)cell {
    NSIndexPath *deleteLeftIndexPath = [self.mainTableView indexPathForCell:cell];
    XYChangeDateController *dateVC = [[XYChangeDateController alloc]init];
    dateVC.CalenderStatus = XYCalenderStatusOut;
    dateVC.pushName = cell.NameLabel.text;
    dateVC.pushRepeat = cell.PushRepeat;
    dateVC.pushTime = cell.cancelPushTime;
    
    //输入日期block
    [dateVC respondsButtonWithDoneEditNotes:^(NSString *text) {
        NSMutableArray *array = [self.dataSource[deleteLeftIndexPath.row] mutableCopy];
        switch (self.XYCellStatus) {
            case XYCellTimeStatus:{
                [self.model.sql updateDataBaseWithTableName:TableName_TheTaskAtHand changeItem:@"finishDate" changeContent:text changeName:array[0]];
            }
                break;
            case XYCellListStatus:{
                [array replaceObjectAtIndex:6 withObject:text];
                [self.model.sql deleteTheDataBaseWithTableName:TableName_MyTask deleteName:array[0]];
                [self.model.sql insertDataSourceToDBwithArray:array tableName:TableName_TheTaskAtHand];
            }
                break;
            case XYCellOkStatus:{
                [array replaceObjectAtIndex:6 withObject:text];
                [self.model.sql deleteTheDataBaseWithTableName:TableName_FinishTask deleteName:array[0]];
                [self.model.sql insertDataSourceToDBwithArray:array tableName:TableName_TheTaskAtHand];
            }
                break;
            default:
                break;
        }
        if (self.XYCellStatus == XYCellTimeStatus) {
            self.dataSource = [NSMutableArray arrayWithArray:[self.model getTheTaskAtHandData]];
            [self.mainTableView reloadData];
        } else {
            [self.dataSource removeObjectAtIndex:deleteLeftIndexPath.row];
            [self.mainTableView deleteRowsAtIndexPaths:@[deleteLeftIndexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
    }];
    
    //取消block
    [dateVC respondsButtonWithDoneEditQuit:^(BOOL isQuit) {
        if (isQuit) {
            [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                cell.myContentLeftConstraint.constant = 0;
                cell.myContentRightConstraint.constant = 0;
                [cell layoutIfNeeded];
            } completion:^(BOOL finished) {
                cell.LeftImageView.alpha = 1.0f;
                cell.RightImageView.alpha = 1.0f;
            }];
        }
    }];
    
    [self presentViewController:dateVC animated:YES completion:nil];
    
}

//向右删除
- (void)deleteTheChoosedCellToRight:(XYTableViewCell *)cell {
    NSIndexPath *currentEditingIndexPath = [self.mainTableView indexPathForCell:cell];
    NSMutableArray *array = [self.dataSource[currentEditingIndexPath.row] mutableCopy];
    switch (self.XYCellStatus) {
        case XYCellTimeStatus:{
            [array replaceObjectAtIndex:6 withObject:@"null"];
            [self.model.sql deleteTheDataBaseWithTableName:TableName_TheTaskAtHand deleteName:array[0]];
            [self.model.sql insertDataSourceToDBwithArray:array tableName:TableName_MyTask];
        }
            break;
        case XYCellListStatus:{
            [array replaceObjectAtIndex:6 withObject:[WiiKit getCurrenTimeForSystem]];
            [self.model.sql deleteTheDataBaseWithTableName:TableName_MyTask deleteName:array[0]];
            [self.model.sql insertDataSourceToDBwithArray:array tableName:TableName_FinishTask];
        }
            break;
        default:
            break;
    }
    [self.dataSource removeObjectAtIndex:currentEditingIndexPath.row];
    [self.mainTableView deleteRowsAtIndexPaths:@[currentEditingIndexPath] withRowAnimation:UITableViewRowAnimationFade];
    
}

#pragma mark - 通知 notification
- (void)registeredNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(respondsToNotification:)
                                                 name:@"notification"
                                               object:nil];
}
// 处理通知，在此处获取从发送通知的控制器传过来的值
- (void)respondsToNotification:(NSNotification *)info {
    self.dataSource = [[self.model getMyTaskData] mutableCopy];
    [self.mainTableView reloadData];
}

- (void)notice:(NSNotification *)info {
    if (self.XYCellStatus == XYCellListStatus) {
        self.dataSource = [[self.model getMyTaskData] mutableCopy];
    } else if (self.XYCellStatus == XYCellTimeStatus) {
        self.dataSource = [[self.model getTheTaskAtHandData] mutableCopy];
    }
    [self.mainTableView reloadData];
}
#pragma mark - setter/getter
- (UITableView *)mainTableView{
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(WiiZero,WiiZero, SCREEN_WIDTH, SCREEN_HEIGHT)];
//        _mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(WiiZero,64, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.rowHeight = 88;
        _mainTableView.separatorStyle = NO;
        [_mainTableView registerNib:[UINib nibWithNibName:@"XYTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:XYIdentifier];
    }
    return _mainTableView;
}

- (WiiHomeModel *)model{
    if (!_model) {
        _model = [[WiiHomeModel alloc]init];
    }
    return _model;
}
@end

